/*******************************************************************************
 * Package: com.song.bigdata.v2
 * Type:    RealTimeOrderTotal
 * Date:    2024-09-20 18:13
 *
 * Copyright (c) 2024 LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.song.bigdata.v2;

import com.song.bigdata.pojo.Order;
import com.song.bigdata.pojo.UserOrderTotal;
import lombok.SneakyThrows;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.ArrayList;
import java.util.List;

/**
 * 功能描述：
 *
 * @author Songxianyang
 * @date 2024-09-20 18:13
 */
public class RealTimeOrderTotal {

    @SneakyThrows
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        List<Order> orders = new ArrayList<>();
        // 添加示例数据
        orders.add(new Order("user1", "order1", 100.0, "2024-09-20 10:00:00"));
        orders.add(new Order("user2", "order2", 200.0, "2024-09-20 10:05:00"));
        orders.add(new Order("user1", "order3", 50.0, "2024-09-20 10:10:00"));
        orders.add(new Order("user3", "order4", 300.0, "2024-09-20 10:15:00"));
        orders.add(new Order("user2", "order5", 150.0, "2024-09-20 10:20:00"));
        orders.add(new Order("user1", "order6", 75.0, "2024-09-20 10:25:00"));

        DataStream<Order> dataStream = env.fromCollection(orders);
        KeyedStream<Order, String> keyedStream = dataStream.keyBy(Order::getUserId);

        keyedStream.reduce(new ReduceFunction<Order>() {
            private static final long serialVersionUID = -6731724642456334745L;

            @Override
            public Order reduce(Order order1, Order order2) throws Exception {
                // 分组后得上一个order数据  和下一个order数据  进行求和
                order1.setAmount(order1.getAmount()+order2.getAmount());
                return order1;
            }
        }).map(new MapFunction<Order, UserOrderTotal>() {
            private static final long serialVersionUID = -8546444938222252739L;

            @Override
            public UserOrderTotal map(Order order) throws Exception {
                return new UserOrderTotal(order.getUserId(),order.getAmount(),"2024-09-20 10:25:00");
            }
        }).print();
        // 执行任务
        env.execute("执行任务");
    }
}
